﻿using System.Reflection;
using System.Text;

public class StringBuilderNoGC
{
    private static FieldInfo sb_strFI;
    private static MethodInfo strInternalSetLen;
    private static readonly object[] objects = new object[1];

    //return the _str reference to sb._str
    public static string getString(StringBuilder sb)
    {
        if (null == sb) return "";

        if (null == sb_strFI)
            sb_strFI = typeof(StringBuilder).GetField("_str", BindingFlags.NonPublic | BindingFlags.Instance);
        if (null == strInternalSetLen)
            strInternalSetLen =
                typeof(string).GetMethod("InternalSetLength", BindingFlags.NonPublic | BindingFlags.Instance);
        var sb_str = (string) sb_strFI.GetValue(sb);
        objects[0] = sb.Length;
        strInternalSetLen.Invoke(sb_str, objects);
        return sb_str;
    }
}